package com.java.jwt.interceptor.utils.interceptor;

import cn.hutool.core.util.URLUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户信息注入拦截器
 * <p>
 * 1、把网关传过来的用户信息注入到BaseContextHandler里面；
 * 2、保存用户操作日志[这个放到权限校验的时候一起保存了。]。
 *
 * @author Wu Qingzhuang
 * @date 2021/06/15 9:44
 */
@Slf4j
public class UserInjectionHandlerInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            if (!(handler instanceof org.springframework.web.method.HandlerMethod)) {
                log.info("not exec!!! url={}", request.getRequestURL());
                return super.preHandle(request, response, handler);
            }
//            // 把网关传过来的token存到上下文
//            BaseContextHandler.setToken(getHeader(request, BaseContextConstants.TOKEN_NAME));
//            // 从token里面解析出用户信息，也放到上下文
//            JwtUser user = JwtUtils.parseToken(BaseContextHandler.getToken());
//            if(Objects.nonNull(user)){
//                BaseContextHandler.setUserId(user.getUserId());
//                BaseContextHandler.setUserCode(user.getUserCode());
//                BaseContextHandler.setUserName(user.getUserName());
//                if(Objects.nonNull(user.getOrgId())){
//                    BaseContextHandler.setOrgId(user.getOrgId());
//                }
//                if(Objects.nonNull(user.getCityOrgId())){
//                    BaseContextHandler.setCityOrgId(user.getCityOrgId());
//                }
//                if(Objects.nonNull(user.getSecondaryOrgId())){
//                    BaseContextHandler.setSecondOrgIdOrgId(user.getSecondaryOrgId());
//                }
//                if(Objects.nonNull(user.getCityOrgCode())){
//                    BaseContextHandler.setCityOrgCode(user.getCityOrgCode());
//                }
//                if(Objects.nonNull(user.getRelationId())){
//                    BaseContextHandler.setRelationId(user.getRelationId());
//                }
//            }
//            String traceId = request.getHeader(BaseContextConstants.TRACE_ID_HEADER);
//            MDC.put(BaseContextConstants.TRACE_ID, StrUtil.isEmpty(traceId) ? "" : traceId);
//            MDC.put(BaseContextConstants.TRACE_USER_ID, String.valueOf(BaseContextHandler.getUserId()));
//            MDC.put(BaseContextConstants.TRACE_URL, request.getRequestURI());
//            log.info("user info Interceptor : {} ,user_id : {}",request.getRequestURI(),BaseContextHandler.getUserId());
        } catch (Exception e) {
            log.warn("url=" + request.getRequestURI(), e);
        }
        return super.preHandle(request, response, handler);
    }

    /**
     * 获取请求头
     */
    private String getHeader(HttpServletRequest request, String name) {
        String value = request.getHeader(name);
        if (StringUtils.isEmpty(value)) {
            return "";
        }
        return URLUtil.decode(value);
    }

    /**
     * 请求完成之后回收BaseContextHandler里面的数据，避免造成oom
     *
     * @author Wu Qingzhuang
     * @date 2021/06/15 9:44
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        BaseContextHandler.remove();
//        // 回收MDC里面的日志
//        MDC.remove(BaseContextConstants.TRACE_ID);
//        MDC.remove(BaseContextConstants.TRACE_USER_ID);
//        MDC.remove(BaseContextConstants.TRACE_URL);
        super.afterCompletion(request, response, handler, ex);
    }
}

